<template>
  <view class="wraps">
    <view class="content">
      <view class="nodate" v-if="listLoading">
        <up-loading-icon></up-loading-icon>
      </view>
      <view v-if="state.taskList && state.taskList.length > 0">
        <indexCardRecord :message="messageObj" :isSign="isSign" @reload="reload" @deleteItem="deleteItem" @onUpdate="add"></indexCardRecord>
      </view>
      <view class="nodate" v-else>
        <img class="img" src="https://ainengli.meilianshuke.com/jkhx/noData.png" alt="" />
        <view class="nodate_text">
          <text class="name">暂无数据</text>
        </view>
      </view>
    </view>
    <up-modal
      :show="state.deleteShow"
      :title="'提示'"
      :closeOnClickOverlay="true"
      :showCancelButton="true"
      :confirmColor="'#FF503D'"
      @confirm="deleteSignsInfo"
      @close="cancel"
      @cancel="cancel"
    >
      <view
        style="width: 100%; font-size: 30rpx; font-weight: 400; color: #4e5969; text-align: center"
        >确认要删除该条记录吗?</view
      >
    </up-modal>

    <view @touchmove.stop.prevent="prevent">
      <up-popup
        :show="show"
        :closeable="true"
        mode="bottom"
        @close="close"
        :custom-style="{ 'max-height': '98vh', overflow: 'auto' }"
        :round="16"
      >
        <HealthPopup 
          :poptype="'others'"
          :healthType="state.type"
          :isClick="state.isClick"
          :empi="userInfo.empi"
          :isShow="show"
          :slideInfoList="slideInfoList"
          :isSign="isSign"
          :uploading="uploading"
          :picInfo="selectPicInfo"
          @onSelectFile="selectFile"
          @onReset="init"
          @onGoit="goit"
          @onSave2="newHealthDateSave"
          @onSave3="saveReportData"
          @onSave4="oldHealthDataUpdate"
          @measurementFun="measurementFun"
          ref="healthPopupRef"
          />
      </up-popup>
    </view>
    <!-- 睡眠录入 -->
    <view @touchmove.stop.prevent="prevent">
      <up-popup
        :show="showSleep"
        :closeable="true"
        mode="bottom"
        @close="close"
        :custom-style="{ 'max-height': '98vh', overflow: 'auto' }"
        :round="16"
      >
        <HealthPopup
        :poptype="'sleep'"
        :healthType="state.type"
        :list="state.healthList"
        :isClick="state.isClick"
        :empi="userInfo.empi"
        :slideInfoList="slideInfoList"
        @onReset="init"
        @onGoit="goit"
        @onSave2="newHealthDateSave"
        @timeSleepFun="timeSleepFun"
        ref="sleepPopupRef"
          />
      </up-popup>
    </view>
    <view @touchmove.stop.prevent="prevent">
      <up-popup
        :show="measurementShow"
        :closeable="true"
        mode="bottom"
        @close="goit"
        :custom-style="{
          'max-height': '98vh',
          overflow: 'auto'
        }"
      >
        <HealthPopup
        :poptype="'tips'"
        :healthType="state.type"
        @onGoit="goit"
        @onReset="init"
          />
      </up-popup>
    </view>
    <!-- sleep 时间 -->
    <view @touchmove.stop.prevent="prevent">
      <up-datetime-picker
        :show="dateSleepShow"
        v-model="state.datetime"
        :closeOnClickOverlay="true"
        :minDate="state.minDate"
        :maxDate="new Date().getTime()"
        mode="datetime"
        @close="closeSleepDateTime"
        @confirm="confirmSleepDateTime"
        @cancel="closeSleepDateTime"
        @change="changeSleepFun"
      />
    </view>
    <view @touchmove.stop.prevent="prevent">
      <up-popup :show="abnormalShow" :round="8" mode="center" @close="abnormalClose">
        <view class="abnormalContent">
          <view class="title"> 异常提醒 </view>
          <text class="content">
            {{ warningMap(state.type) }}
          </text>
          <view class="know" @tap="abnormalClose">知道了</view>
        </view>
      </up-popup>
    </view>
  </view>
</template>

<script setup lang="ts">
import { reactive, computed, ref, watch } from 'vue'
import { healthInfoMapList, healthInfoUpdate } from '@/api/hmm'
import { onLoad, onShow, onReachBottom } from '@dcloudio/uni-app'
import { getNewDetail, getWaterSleepDetail, signsInfoDelete } from './healthPortrait.api'
import { parseTime } from '@/utils/tools'
import indexCardRecord from './components/indexCardRecord'
import HealthPopup from './components/HealthPopup'
import { 
  saveNewIndicator, 
  getSignsList,
  saveReport,
  signStatus,
  uploadCamp,
  saveCampPic
} from './healthPortrait.api'
import { deleteDefecate, getDefecateListByEmpi } from '../../api/defecate'

const healthPopupRef = ref(null)
const sleepPopupRef = ref(null)
const state = reactive({
  type: '',
  filtrate: {
    //请求参数
    size: 20, // 条数
    num: 1 // 页数
  },
  taskList: [], //数据
  show: false,
  inputValue: '',
  maxNum: 100, //最多输入字数
  getObj: {},
  slideRuleType: '',
  loadstatus: 'nomore',
  slideRuleTypeDefault: false,
  tabkeyboardShow: true,
  slideRuleShow: true,
  isClick: false,
  showTest: false,
  deleteShow: false,
  userInfo: {},
  bloodSugarActive: 0,
  current: 60, //刻度指向的位置
  maxValue: 150,
  ruleType: 'cm',
  healthList: {},
  datetime: 0,
  minDate: 0,
  time: '',
  datetimeNew: '',
  wakeupDate: '',
  sleepDate: ''
})
const updateId = ref('')
const listLoading = ref(false)
const abnormalShow = ref<boolean>(false)
const measurementShow = ref(false)
const show = ref(false)
const showSleep = ref(false)
const sleepTimeType = ref('')
const dateSleepShow = ref(false)
const userInfo = ref<any>({})
const messageObj = ref<any>({
  taskList: [],
  type: '',
  loadstatus: 'loadmore'
})
const empi = ref<string>('')
const slideInfoList = ref<any>([])


const swipeRef = ref()
const deleteIndex = ref(0)

onLoad((option: any) => {
  if (option.type) {
    if (option.type == 'blood_pressure') {
      state.type = 'sbp'
    } else if (option.type == 'heart') {
      state.type = 'heart_rate'
    } else if (option.type == 'blood_oxygen') {
      state.type = 'spo2'
    } else if (option.type == 'BMI') {
      state.type = 'bmi'
    } else {
      state.type = option.type
    }
    messageObj.value.type = state.type
  }
  userInfo.value = uni.getStorageSync('userInfo')
    ? JSON.parse(uni.getStorageSync('userInfo')).patientInfo
    : {}

  empi.value = option.empi ? option.empi : userInfo.value.empi
})
onReachBottom(() => {
  if (state.loadstatus != 'nomore') {
    loadMoreData()
  }
})
onShow(() => {
  init()
  getMinTime()
  if (state.type == 'bmi') {
    getStatus()
  }
})

watch(
  () => state.inputValue,
  (newVal, oldVal) => {
    if (newVal && newVal.length > 100) {
      state.inputValue = newVal.substring(0, 100)
    }
  },
  {
    immediate: true
  }
)
const init = () => {
  state.taskList = []
  messageObj.value.taskList = []
  if (
    state.type == 'blood_ketone' ||
    state.type == 'uric_acid' ||
    state.type == 'blood_fat' ||
    state.type == 'liver_function' ||
    state.type == 'blood_sugar'
  ) {
    getNewList()
  } else if (state.type == 'water' || state.type == 'sleep') {
    getWaterSleepList()
  } else if (state.type === 'defecate') {
    getDefecateList()
  } else {
    getList()
  }
}

// 获取数据
const getList = () => {
  if (state.taskList.length == 0) {
    listLoading.value = true
  }
  state.loadstatus = 'loading'
  messageObj.value.loadstatus = 'loading'
  const param = {
    empi: empi.value,
    page: state.filtrate.num,
    limit: state.filtrate.size,
    itemList: []
  }
  if (state.type == 'fbg') {
    const obj1 = 'fbg'
    const obj2 = 'pbg'
    param.itemList.push(obj1)
    param.itemList.push(obj2)
  } else {
    param.itemList.push(state.type)
  }
  getSignsList(param).then((res) => {
    listLoading.value = false
    if (res.code == 0) {
      if (res.data && res.data.length > 0) {
        // 拼接图片地址
        if (state.type == 'bmi') {
          res.data.forEach((val) => {
            if (val.campWieghtPics && val.campWieghtPics.length > 0) {
              val.campWieghtPics.forEach((item) => {
                item.url = item.picBaseUrl + item.picUrl
                item.relativePath = item.picUrl
                item.name = item
                item.status = 'success'
                item.extname = 'png'
              })
            } else {
              val.campWieghtPics = []
            }
          })
        }
        if (state.taskList.length > 0) {
          state.taskList = state.taskList.concat(res.data)
          messageObj.value.taskList = state.taskList
        } else {
          state.taskList = res.data
          messageObj.value.taskList = state.taskList
        }
        if (res.data.length < 20) {
          state.loadstatus = 'nomore'
          messageObj.value.loadstatus = 'nomore'
        } else {
          state.loadstatus = 'loadmore'
          messageObj.value.loadstatus = 'loadmore'
        }
      } else {
        state.loadstatus = 'nomore'
        messageObj.value.loadstatus = 'nomore'
      }
    } else {
      state.filtrate.num--
      state.loadstatus = 'error'
      messageObj.value.loadstatus = 'error'
    }
  })
}
const reload = () => {
  // state.filtrate.num++
  getList()
}
const getNewList = () => {
  listLoading.value = true
  state.loadstatus = 'loading'
  messageObj.value.loadstatus = 'loading'
  const param = {
    empi: userInfo.value.empi,
    indicatorKey: state.type
  }
  getNewDetail(param).then((res: any) => {
    listLoading.value = false
    if (res.code == 0) {
      if (res.data && res.data.length > 0) {
        const seenDates = new Set()
        state.taskList = res.data.map((item) => {
          const date = item.report.checkTime.split(' ')[0] // 提取日期部分
          const time = item.report.checkTime
          if (seenDates.has(date)) {
            // 如果日期已出现，隐藏 checkTime
            return { ...item, report: { ...item.report, checkTime: null, realTime: time } }
          } else {
            // 如果日期未出现，保留 checkTime
            seenDates.add(date)
            return item
          }
        })
        messageObj.value.taskList = state.taskList
        // 这个接口似乎没用分页，并且加载更多也没有加载这个接口，所以先这样改了
        state.loadstatus = 'nomore'
        messageObj.value.loadstatus = 'nomore'
        // if (res.data.length < 20) {
        //   state.loadstatus = 'nomore'
        //   messageObj.value.loadstatus = 'nomore'
        // } else {
        //   state.loadstatus = 'loadmore'
        //   messageObj.value.loadstatus = 'loadmore'
        // }
      } else {
        state.taskList = []
        messageObj.value.taskList = []
        state.loadstatus = 'nomore'
        messageObj.value.loadstatus = 'nomore'
      }
    } else {
      state.filtrate.num--
      state.loadstatus = 'error'
      messageObj.value.loadstatus = 'error'
    }
  })
}

const getWaterSleepList = () => {
  listLoading.value = true
  state.loadstatus = 'loading'
  messageObj.value.loadstatus = 'loading'
  const param = {
    empi: userInfo.value.empi,
    itemList: [state.type],
    page: 1,
    limit: 10
  }
  getWaterSleepDetail(param).then((res: any) => {
    listLoading.value = false
    if (res.code == 0) {
      const seenDates = new Set()
      if (res.data && res.data.length > 0) {
        if (state.type == 'sleep') {
          state.taskList = res.data.map((item: any) => {
            const date = item.collectTime.split(' ')[0]
            if (seenDates.has(date)) {
              return {
                ...item,
                collectTime: null,
                paramValue: JSON.parse(item.paramValue)
              }
            } else {
              seenDates.add(date)
              return {
                ...item,
                paramValue: JSON.parse(item.paramValue)
              }
            }
          })
          // 解决IOS下不兼容yyyy-MM-dd格式问题
          state.taskList.forEach((val) => {
            val.paramValue.sleepTime = parseTime(val.paramValue.sleepTime, '{y}/{m}/{d} {h}:{i}')
            val.paramValue.weekupTime = parseTime(val.paramValue.weekupTime, '{y}/{m}/{d} {h}:{i}')
          })
          messageObj.value.taskList = state.taskList
        } else {
          state.taskList = res.data
          messageObj.value.taskList = state.taskList
        }
        // 这个接口似乎分页没有生效，并且加载更多也没有加载这个接口，所以先这样改了
        state.loadstatus = 'nomore'
        messageObj.value.loadstatus = 'nomore'
        // if (res.data.length < 20) {
        //   state.loadstatus = 'nomore'
        //   messageObj.value.loadstatus = 'nomore'
        // } else {
        //   state.loadstatus = 'loadmore'
        //   messageObj.value.loadstatus = 'loadmore'
        // }
      } else {
        state.taskList = []
        messageObj.value.taskList = []
        state.loadstatus = 'nomore'
        messageObj.value.loadstatus = 'nomore'
      }
    } else {
      state.filtrate.num--
      state.loadstatus = 'error'
      messageObj.value.loadstatus = 'error'
    }
  })
}

const getDefecateList = () => {
  listLoading.value = true
  state.loadstatus = 'loading'
  messageObj.value.loadstatus = 'loading'
  const param = {
    empi: userInfo.value.empi
  }
  getDefecateListByEmpi(param).then((res: any) => {
    listLoading.value = false
    if (res.code == 0) {
      state.taskList = res.data
      messageObj.value.taskList = state.taskList
      state.loadstatus = 'nomore'
      messageObj.value.loadstatus = 'nomore'
    } else {
      state.filtrate.num--
      state.loadstatus = 'error'      
      messageObj.value.loadstatus = 'error'
    }
  })
}
const loadMoreData = () => {
  state.filtrate.num++
  getList()
}

const prevent = () => {}

const measurementFun = () => {
  if (
    state.type == 'bmi' ||
    state.type == 'sbp' ||
    state.type == 'blood_sugar'
  ) {
    measurementShow.value = true
    show.value = false
    showSleep.value = false
  }
}

const oldHealthDataUpdate = async (param: any) => {
  if (state.type == 'bmi' && isSign.value) {
    param.campWieghtPics = getPicList()
  }
  healthInfoUpdate(param)
    .then((res) => {
      uni.hideLoading()
      if (res.code == 0) {
        if (res.data == 'true') {
          show.value = false
          showSleep.value = false
          abnormalShow.value = true
        } else {
          uni.showToast({
            title: '提交成功',
            icon: 'none',
            duration: 2000
          })
          setTimeout(() => {
            show.value = false
            showSleep.value = false
            init()
          }, 2000)
        }
      }
    })
    .catch((err) => {
      state.isClick = false
    })
}
/// 新指标保存
const newHealthDateSave = (param: any) => {
  saveNewIndicator(param)
    .then((res) => {
      uni.hideLoading()
      if (res.code == 0) {
        if (res.data == true && state.type != 'water') {
          show.value = false
          showSleep.value = false
          abnormalShow.value = true
        } else {
          uni.showToast({
            title: '提交成功',
            icon: 'none',
            duration: 1500
          })
          setTimeout(() => {
            show.value = false
            showSleep.value = false
            init()
          }, 2000)
        }
      }
    })
    .catch((err) => {
      state.isClick = false
    })
}
// 保存报告
const saveReportData = (param: any) => {
  saveReport(param)
    .then((res) => {
      uni.hideLoading()
      if (res.code == 0) {
        if (res.data == 'true') {
          show.value = false
          showSleep.value = false
          abnormalShow.value = true
        } else {
          uni.showToast({
            title: '提交成功',
            icon: 'none',
            duration: 1500
          })
          setTimeout(() => {
            show.value = false
            showSleep.value = false
            init()
          }, 2000)
        }
      }
    })
    .catch((err) => {
      state.isClick = false
    })
}

const warningMap = (type: string) => {
  let text = ''
  switch(type) {
    case 'bmi': 
      text = '您的BMI异常，请关注体重数据'
      break
    case 'whr': 
      text = '您的腰臀比数据异常，请关注'
      break
    case 'sbp': 
      text = '您的血压异常，建议您增加监测次数并咨询医生'
      break
    case 'heart_rate': 
      text = '您的心率异常，建议您增加监测次数并咨询医生'
      break
    case 'blood_sugar': 
      text = '您的血糖异常，建议您增加监测次数并咨询医生'
      break
    case 'spo2': 
      text = '您的血氧异常，建议您增加监测次数并咨询医生'
      break
    case 'blood_ketone': 
      text = '您的血酮异常，建议您增加监测次数并咨询医生'
      break
    case 'uric_acid': 
      text = '您的尿酸异常，建议您增加监测次数并咨询医生'
      break
    case 'sleep': 
      text = '您的睡眠时间过短，请注意'
      break
    case 'blood_fat': 
      text = '您的血脂异常，建议您增加监测次数并咨询医生'
      break
    case 'liver_function': 
      text = '您的肝功能异常，建议您增加监测次数并咨询医生'
      break
  }
  return text
}

const abnormalClose = () => {
  abnormalShow.value = false
  init()
}
const setSlideInfo = (type: string, editItem: any) => {
  // 整合健康监测数据
  slideInfoList.value = []
  switch(state.type) {
    case 'bmi':
    slideInfoList.value[0] = {
      value: type == 'edit' && Object.keys(editItem).length !== 0 ? editItem.height 
        :(state.healthList.height.itemValue
        ? Number(state.healthList.height.itemValue)
          : 170),
      maxValue: 250,
      name: '身高',
      unit: 'cm'
    }
    slideInfoList.value[1] = {
      value: type == 'edit' && Object.keys(editItem).length !== 0 ? editItem.weight 
        :(state.healthList.weight.itemValue
        ? Number(state.healthList.weight.itemValue)
          : 65),
      maxValue: 250,
      name: '体重',
      unit: 'kg'
    }
    break
    case 'whr':
    slideInfoList.value[0] = {
      value: type == 'edit' && Object.keys(editItem).length !== 0 ? editItem.waist 
        :(state.healthList.waist.itemValue
        ? Number(state.healthList.waist.itemValue)
          : 85),
      maxValue: 200,
      name: '腰围',
      unit: 'cm'
    }
    slideInfoList.value[1] = {
      value: type == 'edit' && Object.keys(editItem).length !== 0 ? editItem.hip 
        :(state.healthList.hip.itemValue
        ? Number(state.healthList.hip.itemValue)
          : 100),
      maxValue: 200,
      name: '臀围',
      unit: 'cm'
    }
    break
    case 'sbp':
    slideInfoList.value[0] = {
      value: type == 'edit' && Object.keys(editItem).length !== 0 ? editItem.sbp 
        :(state.healthList.sbp.itemValue
        ? Number(state.healthList.sbp.itemValue)
          : 120),
      maxValue: 300,
      name: '收缩压',
      unit: 'mmHg'
    }
    slideInfoList.value[1] = {
      value: type == 'edit' && Object.keys(editItem).length !== 0 ? editItem.dbp 
        :(state.healthList.dbp.itemValue
        ? Number(state.healthList.dbp.itemValue)
          : 80),
      maxValue: 300,
      name: '舒张压',
      unit: 'mmHg'
    }
    slideInfoList.value[2] = {
      value: type == 'edit' && Object.keys(editItem).length !== 0 ? editItem.pulseRate 
        :(state.healthList.pulseRate.itemValue
        ? Number(state.healthList.pulseRate.itemValue)
          : 75),
      maxValue: 180,
      name: '脉搏',
      unit: '次/分'
    }
    break
    case 'heart_rate':
    slideInfoList.value[0] = {
      value: type == 'edit' && Object.keys(editItem).length !== 0 ? editItem.heartRate 
        :(state.healthList.heartRate.itemValue
        ? Number(state.healthList.heartRate.itemValue)
          : 75),
      maxValue: 180,
      name: '心率',
      unit: '次/分'
    }
    break
    case 'blood_sugar':
    slideInfoList.value[0] = {
      value: type == 'edit' && Object.keys(editItem).length !== 0 
        ? editItem.details[0].indicatorValue 
        :state.healthList.pbg && state.healthList.pbg.itemValue
        ? Number(state.healthList.pbg.itemValue)
        :state.healthList.fbg && state.healthList.fbg.itemValue
        ? Number(state.healthList.fbg.itemValue)
          : 5.5,
      maxValue: 30,
      name: '血糖',
      unit: 'mmol/L'
    }
    break
    case 'spo2':
    slideInfoList.value[0] = {
      value: type == 'edit' && Object.keys(editItem).length !== 0 ? editItem.spo2 
        :(state.healthList.spo2.itemValue
        ? Number(state.healthList.spo2.itemValue)
          : 97),
      maxValue: 100,
      name: '血氧饱和度',
      unit: '%'
    }
    break
    case 'blood_ketone':
    slideInfoList.value[0] = {
      value: type == 'edit' && Object.keys(editItem).length !== 0 
        ? editItem.details[0].indicatorValue
        :(state.healthList.blood_ketone && state.healthList.blood_ketone.indicatorList
        ? Number(state.healthList.blood_ketone.indicatorList[0].indicatorValue)
          : 0.17),
      maxValue: 4.0,
      name: '血酮',
      unit: 'mmoL/L'
    }
    break
    case 'uric_acid':
    slideInfoList.value[0] = {
      value: type == 'edit' && Object.keys(editItem).length !== 0 
        ? editItem.details[0].indicatorValue
        :(state.healthList.uric_acid.indicatorList
        ? Number(state.healthList.uric_acid.indicatorList[0].indicatorValue)
          : 200),
      maxValue: 600,
      name: '尿酸',
      unit: 'umol/L'
    }
    break
    case 'water':
    if (state.healthList.water && state.taskList.length > 0) {
      state.healthList.water.itemValue = state.taskList[0].drinkList[0].paramValue
    }
    slideInfoList.value[0] = {
      value: type == 'edit' && Object.keys(editItem).length !== 0 
        ? Number(editItem.paramValue)
        :(state.healthList.water && state.healthList.water.itemValue
        ? Number(state.healthList.water.itemValue)
          : 350),
      maxValue: 4000,
      name: '饮水',
      unit: 'ml'
    }
    break
    case 'blood_fat':
    const listData =
      state.healthList.blood_fat && state.healthList.blood_fat.indicatorList
        ? state.healthList.blood_fat.indicatorList
        : []
    const total_cholesterol = listData.filter((item) => item.indicatorKey == 'total_cholesterol')[0]
    const tg = listData.filter((item) => item.indicatorKey == 'tg')[0]
    const hdlc = listData.filter((item) => item.indicatorKey == 'hdlc')[0]
    const ldlc = listData.filter((item) => item.indicatorKey == 'ldlc')[0]
    slideInfoList.value[0] = {
      value: type == 'edit' && Object.keys(editItem).length !== 0 
        ? editItem.details[0].indicatorValue
        :(total_cholesterol ? Number(total_cholesterol.indicatorValue) : 4.0),
      maxValue: 6.0,
      name: '总胆固醇',
      unit: 'mmol/L'
    }
    slideInfoList.value[1] = {
      value: type == 'edit' && Object.keys(editItem).length !== 0 
        ? editItem.details[1].indicatorValue
        :(tg ? Number(tg.indicatorValue) : 1.0),
      maxValue: 3.0,
      name: '甘油三酯',
      unit: 'mmol/L'
    }
    slideInfoList.value[2] = {
      value: type == 'edit' && Object.keys(editItem).length !== 0 
        ? editItem.details[2].indicatorValue
        :(hdlc ? Number(hdlc.indicatorValue) : 1.3),
      maxValue: 3.0,
      name: '高密度脂蛋白',
      unit: 'mmol/L'
    }
    slideInfoList.value[3] = {
      value: type == 'edit' && Object.keys(editItem).length !== 0 
        ? editItem.details[3].indicatorValue
        :(ldlc ? Number(ldlc.indicatorValue) : 3.0),
      maxValue: 3.0,
      name: '低密度脂蛋白',
      unit: 'mmol/L'
    }
    break
    case 'liver_function':
    const liver_functionData =
      state.healthList.blood_fat && state.healthList.blood_fat.indicatorList
        ? state.healthList.blood_fat.indicatorList
        : []
    const got = liver_functionData.filter((item) => item.indicatorKey == 'got')[0]
    const gpt = liver_functionData.filter((item) => item.indicatorKey == 'gpt')[0]
    const ygt = liver_functionData.filter((item) => item.indicatorKey == 'ygt')[0]
    slideInfoList.value[0] = {
      value: type == 'edit' && Object.keys(editItem).length !== 0 
        ? editItem.details[0].indicatorValue
        :(got ? Number(got.indicatorValue) : 28),
      maxValue: 60,
      name: '谷草转氨酶',
      unit: 'U/L'
    }
    slideInfoList.value[1] = {
      value: type == 'edit' && Object.keys(editItem).length !== 0 
        ? editItem.details[1].indicatorValue
        :(gpt ? Number(gpt.indicatorValue) : 30),
      maxValue: 60,
      name: '谷丙转氨酶',
      unit: 'U/L'
    }
    slideInfoList.value[2] = {
      value: type == 'edit' && Object.keys(editItem).length !== 0 
        ? editItem.details[2].indicatorValue
        :(ygt ? Number(ygt.indicatorValue) : 26),
      maxValue: 60,
      name: 'Y-谷氨酰转肽酶',
      unit: 'U/L'
    }
    break
  }
  slideInfoList.value.forEach((item) => {
    item.init = item.value
    item.currentScore = item.value
  })
}

const add = (name: string, type: string, editItem: any) => {
  if (
    editItem.dataSource != '华为运动健康' || 
    (editItem.report && 
    editItem.report.reportSource && 
    editItem.report.reportSource != '华为运动健康')) {
    if (state.type == 'sleep') {
      showSleep.value = true
      sleepPopupRef.value.add(name, type, editItem)
    } else {
      show.value = true
      healthPopupRef.value.add(name, type, editItem)
    }
    setSlideInfo(type, editItem)
    setSignId(editItem)
  }
}
const timeSleepFun = (date: any, type: string) => {
  console.log('睡眠时间', date, type)
  sleepTimeType.value = type
  showSleep.value = false
  dateSleepShow.value = true
  // state.datetime = parseTime(date, '{y}-{m}-{d} {h}:{i}')
  state.datetime = new Date(date).getTime()
}
const getMinTime = () => {
  const date = new Date()
  date.setFullYear(new Date().getFullYear())
  date.setMonth(0)
  date.setDate(1)
  date.setHours(0)
  date.setMinutes(0)
  state.minDate = date.getTime()
}
// sleep
const closeSleepDateTime = () => {
  showSleep.value = true
  dateSleepShow.value = false
}
const confirmSleepDateTime = () => {
  showSleep.value = true
  dateSleepShow.value = false
  if (state.datetimeNew) {
    if (sleepTimeType.value == 'sleep') {
      state.sleepDate = state.datetimeNew.replace(/\//g, '-')
      sleepPopupRef.value.setSleepTime(state.sleepDate)
    } else {
      state.wakeupDate = state.datetimeNew.replace(/\//g, '-')
      sleepPopupRef.value.setWakeupTime(state.wakeupDate)
    }
  } else {
    if (sleepTimeType.value == 'sleep') {
      state.sleepDate = parseTime(new Date().getTime(), '{y}-{m}-{d} {h}:{i}').replace(/\//g, '-')
      sleepPopupRef.value.setSleepTime(state.sleepDate)
    } else {
      state.wakeupDate = parseTime(new Date().getTime(), '{y}-{m}-{d} {h}:{i}').replace(/\//g, '-')
      sleepPopupRef.value.setWakeupTime(state.wakeupDate)
    }
  }
}
const changeSleepFun = (item) => {
  const data = parseTime(new Date(item.value).getTime(), '{y}-{m}-{d} {h}:{i}')
  state.datetimeNew = data
}
const goit = () => {
  measurementShow.value = false
  if (state.slideRuleShow == true) {
    state.slideRuleShow = !state.slideRuleShow
    setTimeout(() => {
      state.slideRuleShow = !state.slideRuleShow
    }, 20)
  }
  show.value = true
}
const close = () => {
  show.value = false
  showSleep.value = false
}
const deleteItem = (item: any) => {
  if (
    state.type == 'blood_ketone' ||
    state.type == 'blood_sugar' ||
    state.type == 'uric_acid' ||
    state.type == 'liver_function' ||
    state.type == 'blood_fat'
  ) {
    updateId.value = item.report.id
  } else {
    updateId.value = item.id
  }
  state.deleteShow = true
}
const deleteSignsInfo = () => {
  if (state.type === 'defecate') {
    deleteDefecate({ id: updateId.value }).then((res) => {
      state.deleteShow = false
      uni.showToast({
        title: '删除成功',
        icon: 'none',
        duration: 2000
      })
      init()
    })
    return
  }
  let deleteParam = [
    {
      id: updateId.value,
      paramKey: state.type
    }
  ]
  signsInfoDelete(deleteParam).then((res) => {
    state.deleteShow = false
    uni.showToast({
      title: '删除成功',
      icon: 'none',
      duration: 2000
    })
    init()
  })
}
const cancel = () => {
  state.deleteShow = false
  swipeRef.value[deleteIndex.value].closeAll()
}

// 萧山医院上传图片功能
const isSign = ref(false)
const uploading = ref(false)
const selectPicInfo = ref({})

const getStatus = () => {
  let params = {
    empi: userInfo.value.empi,
    campaignCode: 'XS_WEIGHT_LOSS'
  }
  signStatus(params).then((res) => {
    isSign.value = res.data.isSign
  })
}
const setSignId = (item: any) => {
  selectPicInfo.value = item
}
// 选择图片
const selectFile = async (files: any) => {
  uploading.value = true
  const lists = [].concat(files.file)

  let fileListLen = selectPicInfo.value.campWieghtPics.length
  lists.map((item: any) => {
    selectPicInfo.value.campWieghtPics.push({
      ...item,
      status: 'uploading',
      message: '上传中'
    })
  })

  for (let i = 0; i < lists.length; i++) {
    const result: any = await uploadCamp(lists[i].url)
    const item = selectPicInfo.value.campWieghtPics[fileListLen]
    selectPicInfo.value.campWieghtPics.splice(fileListLen, 1, {
      ...item,
      status: 'success',
      message: '',
      url: result.data.relativePath,
      relativePath: result.data.relativePath
    })
    fileListLen++
  }
  uploading.value = false
}
// 图片列表获取
const getPicList = () => {
  let arr = selectPicInfo.value.campWieghtPics.map((val, idx) => {
    return {
      empi: userInfo.value.empi,
      sort: idx,
      picUrl: val.relativePath
    }
  })
  if (selectPicInfo.value.campWieghtPics.length == 0) {
    arr = [{
      empi: userInfo.value.empi,
      sort: 0,
      picUrl: null
    }]
  }
  return arr
}
</script>

<style lang="scss" scoped>
.wraps {
  min-height: 100vh;
  padding-bottom: 64rpx;
  padding-top: 24rpx;

  .content {
    width: calc(100% - 64rpx);
    margin-left: 32rpx;

    ::v-deep .u-swipe-action-item {
      margin-bottom: 24rpx !important;
      border-radius: 12rpx !important;
      &:last-child {
        .min-water {
          border: none;
        }
      }
    }

    ::v-deep .u-swipe-action-item__right__button__wrapper {
      font-size: 24rpx;
      font-weight: 400;
      color: #fff;
      border-radius: 0 12rpx 12rpx 0 !important;
    }
    .nodate {
      text-align: center;
      padding-top: 240rpx;

      .img {
        display: inline-block;
        width: 320rpx;
        height: 240rpx;
      }

      .nodate_text {
        .name {
          display: block;
          margin-top: 10rpx;
          font-size: 28rpx;
          color: #666;
          text-align: center;
        }
      }
    }
  }

  ::v-deep .u-popup {
    .u-popup__content {
      overflow: hidden;

      .abnormalContent {
        width: 80vw;

        .title {
          padding: 40rpx 32rpx 0;
          font-size: 34rpx;
          font-weight: 700;
          color: #1d2129;
          text-align: center;
        }

        .content {
          display: block;
          padding: 15rpx 32rpx 40rpx;
          font-size: 30rpx;
          color: #4e5969;
          text-align: center;
          border-bottom: 2rpx solid #e5e6eb;
        }

        .know {
          height: 88rpx;
          font-size: 32rpx;
          line-height: 88rpx;
          color: #00d1b6;
          text-align: center;
        }
      }
    }

    .u-popup__content__close {
      top: 40rpx;

      .uicon-close {
        font-size: 32rpx !important;
        line-height: 32rpx !important;
      }
    }
  }

  ::v-deep
    .u-popup
    .u-slide-up-enter-to
    .u-picker
    .u-picker__view__column
    .u-picker__view__column__item {
    line-height: 34px !important;
  }

  ::v-deep .u-popup .u-slide-up-enter-active {
    overflow: hidden;
    border-top-left-radius: 32rpx !important;
    border-top-right-radius: 32rpx !important;

    .u-toolbar {
      .u-toolbar__wrapper__confirm {
        color: #00d1b6 !important;
      }
    }
  }

  ::v-deep .u-popup .u-slide-up-enter-to .u-picker .u-picker__view {
    height: 400px !important;
  }

  ::v-deep .u-safe-area-inset-bottom {
    padding-bottom: 0 !important;
  }
}

.food-type {
  display: inline-block;
  padding: 4rpx 20rpx 2rpx;
  margin-left: 16rpx;
  font-size: 24rpx;
  font-weight: 400;
  color: #666;
  background: #f5f5f5;
  border-radius: 20rpx 4rpx;
}

.source {
  font-size: 26rpx;
  color: #999;
}
</style>
